package cn.itcast.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author:王亚栋
 * @Date: 2023/7/3 下午7:54
 * @Version:1.0
 * 权限验证过滤器
 */
//@Component
@Slf4j(topic = "AccessFilter")
public class AccessFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("经过权限验证过滤器...");

        //获取请求参数token
        String token = exchange.getRequest().getQueryParams().getFirst("token");

        log.info("token is {}",token);
        //业务逻辑处理
        if (null == token){

            log.error("token is null ...");

            ServerHttpResponse response = exchange.getResponse();

            //响应类型
            response.getHeaders().add("Content-Type","application/json;charset=utf-8");

            //设置状态码为401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            //响应内容
            String message = "{\"message\":\"" + HttpStatus.UNAUTHORIZED.getReasonPhrase() + "\"} ";

            DataBuffer dataBuffer = response.bufferFactory().wrap(message.getBytes());

            //请求结束，不再继续向下请求
            return response.writeWith(Mono.just(dataBuffer));
        }

        log.info("Token is Ok!");

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {

        return 2;
    }
}
